import { ref, watch, onMounted } from 'vue'
import type { FollowType } from '@/types/consult'
import { showSuccessToast, showImagePreview, showFailToast } from 'vant'
import { followDcoctor, getPrescriptionPic } from '@/api/consult'
import { useClipboard } from '@vueuse/core'
import { getMedicalOrderDetail } from '@/api/medicine'
import type { OrderDetail } from '@/types/medicine'
import { useRoute } from 'vue-router'

const useFollow = (type: FollowType = 'doc') => {
  const loading = ref(false)
  const follow = async (doc: { id: string; likeFlag: 0 | 1 }) => {
    loading.value = true
    try {
      await followDcoctor(doc.id, type)
      doc.likeFlag = doc.likeFlag === 1 ? 0 : 1
      showSuccessToast(doc.likeFlag === 1 ? '关注成功' : '取关成功')
    } finally {
      loading.value = false
    }
  }

  return {
    loading,
    follow,
  }
}

const useLookPre = () => {
  const lookPre = async (id?: string) => {
    try {
      if (!id) return
      //const {data}=await getPrescriptionPic(id!)
      const { data } = await getPrescriptionPic(id)
      console.log('处方图片', data.url)
      showImagePreview([data.url])
    } catch (error) {
      console.log(error)
    }
  }
  return {
    lookPre,
  }
}

const useCopy = () => {
  const { copy, copied, isSupported } = useClipboard()

  const onCopy = (copyText: string) => {
    if (!isSupported.value) showFailToast('未授权,不支持')
    copy(copyText)
  }

  watch(copied, () => {
    if (copied.value) showSuccessToast('已复制')
  })
  return {
    onCopy,
  }
}

const useMedicineDetail = (id: string) => {
  const route = useRoute()
  const order = ref<OrderDetail>()

  onMounted(async () => {
    const { data } = await getMedicalOrderDetail(id)
    order.value = data
  })
  return {
    order,
  }
}

export { useFollow, useLookPre, useCopy, useMedicineDetail }
